<?php

namespace IDock\Insurance\ACIC\Response;

use IDock\Http\Response;
use IDock\Printer\EPolicyDownloadPrinter;
use IDock\Printer\ProposalRecallPrinter;

class EPolicyDownloadResponse extends AllACICResponse
{
    public function resolve(): Response
    {
        $body = $this->getBody();

        if ($body) {
            libxml_disable_entity_loader(false);
            $body = simplexml_load_string($body);

            $body = $this->objectToArray($body);

            $errorCode = $body['Head']['ErrorCode'] ?? '';

            if ($errorCode !== '0000') {

                $errorMessage = $body['Head']['ErrorMessage'] ?? '未知错误';

                if ($errorMessage == '电子保单正在生成中，请稍候') {
                    $proposalRecallPrinter = new EPolicyDownloadPrinter();
                    $proposalRecallPrinter->doing = true;
                    $proposalRecallPrinter->finish = false;
                    $this->printer = $proposalRecallPrinter;
                } else {
                    $this->setError($errorMessage);
                }

                return  $this;
            }

            $this->setBody($body['Body'] ?? '');
        }
        return $this;
    }

    public function printerInit(): Response
    {
        if ($this->printer) {
            return  $this;
        }

        $proposalRecallPrinter = new EPolicyDownloadPrinter();
        $proposalRecallPrinter->finish = !$this->getError();
        $proposalRecallPrinter->doing = false;
        $proposalRecallPrinter->url = $this->get('Url');

        $this->printer = $proposalRecallPrinter;
        return  $this;
    }
}